package megrez.boot.autoconfigure.aliyun.mail;

import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import com.aliyun.dm20151123.Client;
import com.aliyun.dm20151123.models.SingleSendMailRequest;
import com.aliyun.dm20151123.models.SingleSendMailResponse;

import lombok.RequiredArgsConstructor;
import megrez.boot.autoconfigure.aliyun.mail.MailProperties.RequestParams;

/**
 * 邮件发送服务
 *  
 * @author Lucky Yang
 * @since 2.6.9
 */
@RequiredArgsConstructor
public class MailSenderClient {
    private final Client client;
    private final MailProperties properties;

    public SingleSendMailResponse singleSendMail(MailSenderMessage message) throws Exception {
        if (message == null) {
            throw new IllegalArgumentException("MailSenderMessage instance is null");
        }
        if (CollectionUtils.isEmpty(message.getMailAddresses())) {
            throw new IllegalArgumentException("Mail address list is empty");
        }

        RequestParams params = properties.getRequestParams();
        SingleSendMailRequest request = new SingleSendMailRequest();
        if (StringUtils.hasText(params.getAccountName())) {
            request.setAccountName(params.getAccountName());
        }
        if (StringUtils.hasText(params.getFromAlias())) {
            request.setFromAlias(params.getFromAlias());
        }
        if (params.getAddressType() != null) {
            request.setAddressType(params.getAddressType());
        }
        if (StringUtils.hasText(params.getTagName())) {
            request.setTagName(params.getTagName());
        }
        if (params.getReplyToAddress() != null) {
            request.setReplyToAddress(params.getReplyToAddress());
        }
        if (StringUtils.hasText(params.getClickTrace())) {
            request.setClickTrace(params.getClickTrace());
        }

        request.setToAddress(String.join(",", message.getMailAddresses()));
        request.setSubject(message.getSubject());
        if (message.isTextable()) {
            request.setTextBody(message.getBody());
        } else {
            request.setHtmlBody(message.getBody());
        }

        return client.singleSendMail(request);
    }
}
